#include "Login-ly.h"
#include "ui_Login-ly.h"
#include <QComboBox>
#include <QVBoxLayout>
#include <QDebug>
#include <QPixmap>
#include <QPainter>
#include <QRegularExpressionValidator>
#include <QRegularExpression>
#include <QSettings>
#include <QCryptographicHash>
#include <QSqlError>
#include <QIcon>
#include <QTextCodec>
#include <QCompleter>
#include <QLabel>
#include <QMouseEvent>
#include <QSqlRecord>
#include <QMessageBox>
#include <QFile>
#include <QImage>
#include <QBuffer>
#include <QDebug>
#include <QGraphicsOpacityEffect>
#include <QPropertyAnimation>



Login_ly::Login_ly(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login_ly)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::Window);
    setAttribute(Qt::WA_TranslucentBackground);

    setWindowIcon(QIcon(":/UIsources/logo2.png"));




    ui->setupUi(this);
    ui->pushButton->setFlat(true);
    ui->pushButton_2->setFlat(true);



    ui->label_2->setPixmap(QPixmap(":/UIsources/add.png"));
   QString path =  QCoreApplication::applicationDirPath();


//123456@163.com
   mk_info_dir(path);
   //变成 info 目录地址
   QString ddd=path+"/info";
   //创建账户名的文件夹
   QString image_path= mk_dir(ddd,"123456@163.com");
   //用于存储用户头像的目的文件
   QString result=image_path+"/1.png";
   //存储用户头像
   store_image(result);
   store_account_passwd("123456@163.com"," abc123456#",ddd);

   //read_account("C:/Users/34869/Desktop/info","33333");
   set_comBox(ddd);
   QPixmap pixmap = ui->comboBox->itemIcon(ui->comboBox->currentIndex()).pixmap(ui->label_2->size());
   ui->label_2->setPixmap(pixmap);

//123456789@qq.com
    image_path=mk_dir(ddd,"123456789@qq.com");
    result=image_path+"/1.png";
    store_image(result);
    store_account_passwd("123456789@qq.com"," abc123456#",ddd);


    read_the_last_login();
}

Login_ly::~Login_ly()
{

    if(this->Stu)
        delete this->Stu;
    if(this->Set)
        delete this->Set;
     delete ui;
}

//自动登录
void Login_ly::on_autologin_clicked()
{
    if(ui->remember->checkState() == Qt::Unchecked)
     {
         ui->remember->setChecked(true);
     }
    if(ui->autologin->isChecked())
    {
        autologin = true;
    }
    else
    {
        autologin = false;
    }
}

//学生身份选择
void Login_ly::on_pushButton_clicked()
{
        ui->pushButton->setCheckable(true);
        ui->pushButton->setStyleSheet("QPushButton{color:black;}" "QPushButton:checked{color:red;}" );
        if (ui->pushButton->isChecked()) {
            // 如果按钮1被选中，禁用按钮2
            ui->pushButton_2->setEnabled(false);
        } else {
            // 如果按钮1没有被选中，启用按钮2
            ui->pushButton_2->setEnabled(true);
        }

}

//老师身份选择
void Login_ly::on_pushButton_2_clicked()
{
    ui->pushButton_2->setCheckable(true);
    ui->pushButton_2->setStyleSheet("QPushButton{color:black;}" "QPushButton:checked{color:red;}" );
    if (ui->pushButton_2->isChecked()) {
        // 如果按钮2被选中，禁用按钮1
        ui->pushButton->setEnabled(false);

    } else {
        // 如果按钮2没有被选中，启用按钮1
        ui->pushButton->setEnabled(true);
    }
}

//记住密码
void Login_ly::on_remember_clicked()
{
    if(ui->autologin->checkState() == Qt::Checked)
     {
         ui->remember->setChecked(true);
     }
    if(ui->remember->isChecked())
    {
        remeberPasswd= true;
    }
    else
    {
        ui->passwd->clear();
        remeberPasswd= false;
    }
}

//
void Login_ly::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)// 检查是否是左键
    {
        m_dragging = true;// 设置拖拽标志
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();// 记录鼠标点击时相对于窗口左上角的位置
        event->accept();// 接受事件
    }
}

void Login_ly::mouseMoveEvent(QMouseEvent *event)
{
    if (m_dragging && (event->buttons() & Qt::LeftButton)) // 检查是否正在拖拽且鼠标左键按下
    {
        move(event->globalPos() - m_dragPosition); // 移动窗口到新的位置
        event->accept();// 接受事件
    }
}

void Login_ly::mouseReleaseEvent(QMouseEvent *event)
{
    m_dragging = false;// 拖拽结束
}

//注册
void Login_ly::on_regiter_clicked()
{
    this->s = new SignUpWidget;
    this->close();
    this->s->show();
}

//账号
void Login_ly::on_comboBox_currentIndexChanged(const QString &arg1)
{

    //QIcon icon =(ui->comboBox->itemIcon(ui->comboBox->currentIndex()));
    QPixmap pixmap = ui->comboBox->itemIcon(ui->comboBox->currentIndex()).pixmap(ui->label_2->size());

    QPixmap image(ui->label_2->width(),ui->label_2->width());
    image.fill(Qt::transparent);

    QPainter painter(&image);//在image上剪裁原图，最终把剪裁的园放到label里
    //设置画笔：刷一张图片
    painter.setBrush(pixmap.scaled(ui->label_2->width(),ui->label_2->width(),Qt::KeepAspectRatioByExpanding));
    painter.drawEllipse(0,0,ui->label_2->width(),ui->label_2->width());
    ui->label_2->setPixmap(image);
    QStringList name = ui->comboBox->currentText().split(" ");
    ui->account->setText(name.first());
}

//登录
void Login_ly::on_login_clicked()
{

     QSqlQuery query;
     QString sql = "select ident from log where username = '";
     if(ui->pushButton->isChecked())
     {

         QString username1 = ui->account->text();
         sql += username1 + "' and passwd = '";
         QString password1 = ui->passwd->text();

         sql += password1;
         sql += "'";

         qDebug()<<sql<<endl;
           if (query.exec(sql))
           {
               if(query.next())
               {
                   this->Stu = new StudentWidget(username1,nullptr);

                   store_account_passwd(username1,password1,QCoreApplication::applicationDirPath() + "/info");
                      remeber_the_last_login();
                   this->close();
                   this->Stu->show();
               }

           } else {
               // 登录失败，弹出提示
               QMessageBox::warning(this, "登录失败", "用户名或密码错误，请重试！");
           }
     }

     else if(ui->pushButton_2->isChecked())
     {
         QString username2 = ui->account->text();
         sql += username2 + "' and passwd = '";
         QString password2 = ui->passwd->text();

         sql += password2;
         sql += "'";
         if (query.exec(sql))
         {
             if(query.next())
             {
                 //this->Tea = new home_widget(username2);

                 store_account_passwd(username2,password2,QCoreApplication::applicationDirPath() + "/info");
                    remeber_the_last_login();
                 this->close();
                 //this->Tea->show();
             }

         } else {
             // 登录失败，弹出提示
             QMessageBox::warning(this, "登录失败", "用户名或密码错误，请重试！");
         }
       }else {
         // 登录失败，弹出提示
         QMessageBox::warning(this, "身份选择", "请选择用户身份！");
        }

}

//配置
void Login_ly::on_settingButton_clicked()
{
    this->Set = new UserMysql;
    this->hide();
    this->Set->show();

}

//退出
void Login_ly::on_close_button_clicked()
{
    this->close();
}

//创建本地账号存储文件夹
void Login_ly::mk_info_dir(const QString &path)
{
    //C:/Users/PYG/Desktop/info
    QDir dir;
    dir.mkpath(path+"/info");
    if(dir.exists())
    {

    }else
    {
        //没有info文件夹，新建一个info 文件夹
        qDebug()<<"创建info文件夹"<<endl;
        dir.mkdir(path+"/info");
    }
}

//创建每个账号的文件夹
QString Login_ly::mk_dir(const QString &path, const QString &dir_name)
{
    //C:/Users/PYG/Desktop/info
    QDir dir;
    QString result=path +"/"+dir_name;
    dir.mkpath(result);
    //根据账号名创建对应命名的文件夹
    dir.mkdir(result);

    return result;
    //C:/Users/PYG/Desktop/info/1050410250/1.txt  1.jpg
    //dir.mkdir("1.txt");
    //QString text_path="1.txt";
    //QFile file(text_path);
}


//存储照片
void Login_ly::store_image(  QString &path)
{

    QByteArray  array;
    QBuffer buffer(&array);//QT缓冲区对象
    buffer.open(QIODevice::WriteOnly);//以只写形式打开缓冲区

    //待存储的图像

    (*ui->label_2->pixmap()).toImage().save(&buffer,"PNG");//以PNG格式存入缓冲区


    QFile file_w(path);
    file_w.open(QIODevice::WriteOnly);
    // 写入目标文件
    qint64 bytesWritten = file_w.write(array);
    if (bytesWritten == array.size())
    {
            qDebug() << "File copied manually successfully!";
     } else
     {
            qDebug() << "Error occurred while copying the file.";
    }
    file_w.close();
}

//存储账号密码
void Login_ly::store_account_passwd(const QString &account, const QString &passwd,const QString &path)
{

    QFile file_w(path +"/"+ account +"/1.txt");
    file_w.open(QIODevice::WriteOnly);
    QTextStream out(&file_w);

        out<<account;
        out<<passwd;

        file_w.close();
}

//读本地文件的账号照片
void Login_ly::read_image(const QString &path,const QString &account)
{
    QDir dir(path);
    QStringList folders = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

    foreach(const QString &folder,folders)
    {
        if(folder==account)
        {
            QString fullPath = dir.filePath(folder);
            QString image_path=fullPath+"/1.jpg";

            QFile file_r(image_path);
            file_r.open(QIODevice::ReadOnly);
            QByteArray array=file_r.readAll();

            QPixmap pixmap;
            pixmap.loadFromData(array);
            ui->label->setPixmap(pixmap);
        }
    }

}

void Login_ly::read_account(const QString &path,const QString &account)
{

    QDir dir(path);

    QStringList folders = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

    foreach(const QString &folder,folders)
    {
        if(folder==account)
        {
            QString fullPath = dir.filePath(folder);
            QString account_path=fullPath+"/1.txt";


            QFile file_r(account_path);
            file_r.open(QIODevice::ReadOnly);
            QTextStream in(&file_r);
            QString line = in.readLine();
            QStringList data = line.split(" ");
            if(!data.isEmpty())
            {
                qDebug()<<data[0];
                qDebug()<<data[1];
            }
        }
    }
}


void Login_ly::set_comBox(const QString &path)
{

    int row = ui->comboBox->count();
    QDir dir(path);
    QStringList folders = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

    foreach(const QString &folder,folders)
    {

        QFile file_r(path+"/"+folder +"/1.txt");
        file_r.open(QIODevice::ReadOnly);
        QTextStream in(&file_r);
        QString line = in.readLine();
        QStringList data = line.split(" ");
        ui->comboBox->insertItem(row,data[0]);
        file_r.close();

        QString fullPath = dir.filePath(folder);
        QString image_path=fullPath+"/1.png";
        QFile image_r(image_path);
        image_r.open(QIODevice::ReadOnly);
        QByteArray array=image_r.readAll();

        QPixmap pixmap;
        pixmap.loadFromData(array);

       // ui->label_2->setPixmap(pixmap.scaled(ui->label_2->size()));
        QIcon icon = (QIcon)pixmap;
        ui->comboBox->setItemIcon(row,icon);
        image_r.close();

        row++;

    }
}

void Login_ly::remeber_the_last_login()
{
    if(ui->remember->isChecked() || ui->autologin->isChecked())
    {
        QString path = QCoreApplication::applicationDirPath();
        qDebug()<<path<<"llllllllllllllllllllllllll"<<endl;
        QString result=path+"/info";
        qDebug()<<result<<"ppppppppppppppppppppppppp"<<endl;
        QString txt_path=result+"/111111.txt";
        QFile file_w(txt_path);
        file_w.open(QIODevice::WriteOnly );
        QTextStream out(&file_w);
        if(ui->remember->isChecked()&&ui->autologin->isChecked()==false)
        {

            //记住密码状态
            out<<"1";
            out<<" ";

            //记住账号状态
            out<<"0";
            out<<" ";

            //记住账号
            out<<ui->account->text();
            out<<" ";
            //记住密码
            out<<ui->passwd->text();
            qDebug()<<"remember            "<<ui->passwd->text();
        }else if(ui->autologin->isChecked())
        {
            //记住密码状态
            out<<"1";
            out<<" ";

            //记住账号状态
            out<<"1";
            out<<" ";

            //记住账号
            out<<ui->account->text();
            out<<" ";
            //记住密码
            out<<ui->passwd->text();
            qDebug()<<"remember            "<<ui->passwd->text();
        }

        file_w.close();
    }
}

void Login_ly::read_the_last_login()
{
    QString path = QCoreApplication::applicationDirPath();
    qDebug()<<path<<"llllllllllllllllllllllllll"<<endl;
    QString result=path+"/info";
    qDebug()<<result<<"ppppppppppppppppppppppppp"<<endl;
    QString txt_path=result+"/111111.txt";
    QFile file_r(txt_path);
    file_r.open(QIODevice::ReadOnly);

    if(file_r.size()==0)
     {
         return ;
     }

    QTextStream in(&file_r);
    QString line = in.readLine();
    QStringList data = line.split(" ");
    if(!data.isEmpty())
    {
        qDebug()<<data[0];
        qDebug()<<data[1];
        qDebug()<<data[2];
        qDebug()<<data[3];
        ui->account->setText(data[2]);
        ui->passwd->setText(data[3]);
        if(data[1]=="1")
        {
            ui->autologin->setChecked(true);
            ui->remember->setChecked(true);
            ui->pushButton->setChecked(true);
            this->on_login_clicked();
        }else if(data[1]=="0" && data[0]=="1")
        {
            ui->remember->setChecked(true);
        }else
        {
            ui->autologin->setChecked(false);
            ui->remember->setChecked(false);
        }


    }
}

